<?php

namespace app\api\controller;

use app\common\library\common;
use think\facade\Db;
use think\Request;
use think\Response;

class Till extends Wap
{

    public function ce($curl)
    {
        $data = (get_headers($curl));

        $da = (explode('object_id=', $data[6]));
        $d = (explode('&', $da[1]));
        return ($d[0]);
    }

    /**
     * 兑换
     * @param Request $request
     * @return void
     */
    public function index(Request $request)
    {
        if (request()->isPost()) {

            $user = $this->checkToken();
            $post = $request->param();
            $receipt_code = trim($post['receipt_code']);  //核销码
            $room_list = Db::name('customer_trill')->where('store_id', $post['room_id'])->find();


            if (!$room_list) {
                $arr['code'] = 101;
                $arr['message'] = '当前门店未配置抖音验券信息,请切换门店后验券';
                Response::create($arr, 'json')->send();
                exit();
            }


            if ($room_list['expires_in'] < time()) {
                $data['client_key'] = $room_list['client_key'];
                $data['client_secret'] = $room_list['client_secret'];
                $data['grant_type'] = "client_credential";

                $header = array(
                    'Content-Type:' . 'multipart/form-data'
                );
                $url = "https://open.douyin.com/oauth/client_token/";

                $res = common::curl_post2($url, $data, $header);

                $return = json_decode($res, true);

                if ($return['message'] == "success") {

                    $da['access_token'] = $return['data']['access_token'];
                    $da['expires_in'] = time() + 7000;
                    $access_token = $da['access_token'];
                    Db::name('customer_trill')->where('store_id', $post['room_id'])->update($da);

                }
            } else {
                $access_token = $room_list['access_token'];
            }

            $header = array(
                'Content-Type:' . 'application/json',
                'access-token:' . $access_token
            );
            if (preg_match("/^(http:\/\/|https:\/\/).*$/", $receipt_code)) {
                $encrypted_data = $this->ce($post['receipt_code']);
                $url = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/prepare/?encrypted_data=" . $encrypted_data;

            } else {
                $url = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/prepare/?code=" . $receipt_code;

            }
            $res = common::curl_get($url, $header);

            $return = json_decode($res, true);

            if (isset($return['data']['certificates'])) {
                $certificates = $return['data']['certificates'];
                if ($certificates) {
                    $sku = $return['data']['certificates'][0]['sku'];
                    $goods_id = $sku['sku_id'];
                    if ($goods_id) {

                        $card_where['trill_id'] = $goods_id;
                        $card_where['mark'] = 1;
                        if($post['coupontype']==2){
                            $card_list = Db::name('pricecoupon')->where($card_where)->find();
                        }else{
                            $card_list = Db::name('coupon')->where($card_where)->find();
                        }

                    }


                    // 查询对应的兑换
                    if (!$card_list) {

                        $arr['code'] = 0;
                        $arr['message'] = '暂无兑换的优惠卡,请稍后再试';
                        Response::create($arr, 'json')->send();
                        exit();
                    }
                    $encrypted_code = $return['data']['certificates'][0]['encrypted_code'];
                    $verify_token = $return['data']['verify_token'];
                    $url = "https://open.douyin.com/goodlife/v1/fulfilment/certificate/verify/";

                    $ya['verify_token'] = $verify_token;
                    $ya['poi_id'] = $room_list['poi_id'];
                    $ya['encrypted_codes'][] = $encrypted_code;


                    $res = common::curl_post2($url, json_encode($ya), $header);
                    $return = json_decode($res, true);

                    if (!isset($return['data'])) {
                        $arr['code'] = 0;
                        $arr['message'] = '此券已核销';
                        Response::create($arr, 'json')->send();
                        exit();
                    }

                    if ($return['data']['error_code'] == 0) {

                        if($return['data']['verify_results'][0]['result']!=0){
                            $arr['code'] = 0;
                            $arr['message'] = $return['data']['verify_results'][0]['msg'];
                            Response::create($arr, 'json')->send();
                            exit();
                        }
                        $insert['user_id'] = $user['id'];
                        $insert['receipt_code'] = $receipt_code;
                        $insert['status'] = 0;
                        $insert['content'] = $res;
                        $insert['admin_id'] = $post['room_id'];
                        $insert['create_time'] = time();
                        $insert['crad_id'] = $card_list['id'];
                        DB::name('mini_tilll_code_list')->insert($insert);
                        //查询期限卡 添加订单信息
                        $dataCoupon = array(
                            'create_time' => time(),
                            'coupon_id' => $card_list['id'],
                            'user_id' => $user['id'],
                            'type' => 3,
                            'end_time' => $card_list['end_time'],
                            'add_time' => $card_list['add_time'],
                            'price' => $card_list['price'],
                            'store_id' => $post['room_id'],
                        );

                        if($post['coupontype']==2){
                            $dataCoupon['hours_add_time']=$card_list['hours_add_time'];
                            $dataCoupon['hours_end_time']=$card_list['hours_end_time'];
                            $dataCoupon['shichang']=$card_list['shichang'];
                            $dataCoupon['course_id']=$card_list['course_id'];
                            $dataCoupon['order_on']=$receipt_code;
                            if (Db::name('mini_user_pricecoupon')->insert($dataCoupon)) {
                                // 更新领取数量
                                $coi = array(
                                    'surplus_num' => $card_list['num'] - $card_list['receive_num'] - 1,
                                    'receive_num' => $card_list['receive_num'] + 1,
                                );

                                Db::name('pricecoupon')->where('id', $card_list['id'])->update($coi);
                                $arr['code'] = 200;
                                $arr['message'] = '核销成功';
                                Response::create($arr, 'json')->send();
                                exit();
                            }

                        }else{
                            if (Db::name('mini_user_coupon')->insert($dataCoupon)) {
                                // 更新领取数量
                                $coi = array(
                                    'surplus_num' => $card_list['num'] - $card_list['receive_num'] - 1,
                                    'receive_num' => $card_list['receive_num'] + 1,
                                );
                                Db::name('coupon')->where('id', $card_list['id'])->update($coi);
                                $arr['code'] = 200;
                                $arr['message'] = '核销成功';
                                Response::create($arr, 'json')->send();
                                exit();
                            }

                        }


                    }else{
                        $arr['code'] = 0;
                        $arr['message'] = $return['data']['description'];
                        Response::create($arr, 'json')->send();
                        exit();

                    }
                } else {


                    $arr['code'] = 0;
                    $arr['message'] = '此券已核销';
                    Response::create($arr, 'json')->send();
                    exit();
                }

            } else {

                $arr['code'] = 0;
                $arr['message'] = $return['data']['description'];
                Response::create($arr, 'json')->send();
                exit();
            }


        }

    }


}